import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:ls_work/model/activity/activity_model.dart';

import '../../model/decode_qrcode_model.dart';
import '../../net/response/activity/ISignListData.dart';
import '../../net/response/activity/activity_sign_in_list_data.dart';
import '../../util/utils.dart';

class ActivitySignInViewModel extends BaseListViewModel<ActivitySignInListData> {
  final int type;
  final String activityId;
  ActivitySignInViewModel(BuildContext context,{required this.type,required this.activityId}) : super(context);

  DecodeQrcodeModel model = new DecodeQrcodeModel();

  var activityModel = ActivityModel();

  var searchName = "";


  @override
  Future<List<ActivitySignInListData>> requestListData() async {
    return type == 0? await activityModel.oldSignList(activityId: activityId,page: page,rows: 9999,humanNameLikeM: searchName):
    await activityModel.volunteerSignList(activityId: activityId,page: page,rows: 9999,humanNameLikeM: searchName);
  }

  Future<void> searchOldById(dynamic humanid) async {
    var list =  type == 0? await activityModel.oldSignList(activityId: activityId,humanid: humanid):
    await activityModel.volunteerSignList(activityId: activityId,humanid: humanid);
    if(list.isNotEmpty){
      signInActivity(list[0].id);
    }else{
      showToast("未报名该活动");
    }
  }

  @override
  void onCreated() {
    super.onCreated();
    requestRefresh();
  }

  Future<void> signInActivity(dynamic humanid) async {
    showLoadingDialog(msg: '提交中...');
    try{
      await activityModel.submitSignIn(humanid);
      hideDialog();
      showToast("签到成功");
      requestRefresh();
    }catch(e){
      showToast(NetErrorUtils.getNetError(e));
      hideDialog();
    }
  }


  ///扫码跳转
  Future<void> scanCode() async {
    var result = await Utils.scan();
    if (result != null) {
      _scanResult(result);
    }
  }

  Future<void> _scanResult(String code) async {
    showLoadingDialog();
    try {
      var data = await model.decoed(code);

      switch (data.typeCode) {
        case 1:
          var customerId =  data.id!.toInt();
          await searchOldById(customerId);
          break;
        default:
          showToast("请扫描长者二维码");
          break;
      }
      hideDialog();
    } catch (e) {
      hideDialog();
      showToast(NetErrorUtils.getNetError(e));
    }
  }

}
